/* eslint-disable no-console */
// @ts-nocheck
const net = require('net');
const axios = require('axios');

/**
 * 此文件为毕设硬件外接专用，纯 hardcode 写法
 * 主要使用 tcp 建立连接，硬件侧发送数据到该中间层，进行处理后进行接口的上报处理
 * 请勿改动 or 删除，有问题找 @郑智宇
 */
const HENHOUSE_A = '1';
const HENHOUSE_B = '2';
const HENHOUSE_C = '3';
const QUALITY_A = '4';
const QUALITY_B = '5';
const QUALITY_C = '6';
const henhouseMap = new Map([
  [HENHOUSE_A, 'A'],
  [HENHOUSE_B, 'B'],
  [HENHOUSE_C, 'C'],
  [QUALITY_A, 'A'],
  [QUALITY_B, 'B'],
  [QUALITY_C, 'C']
]);
const client = new net.Socket();

function getDate(date) {
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hours = date.getHours(); //时
  let minutes = date.getMinutes(); //分
  let seconds = date.getSeconds(); //秒

  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  if (day >= 0 && day <= 9) {
    day = '0' + day;
  }
  if (hours >= 0 && hours <= 9) {
    hours = '0' + hours;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = '0' + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = '0' + seconds;
  }
  return (
    year + '-' + month + '-' + day + ' ' + `${hours}:${minutes}:${seconds}`
  );
}

//3.连接tcp服务器：
client.connect(1234, '119.91.26.59', () => {
  console.log('服务连接成功');
  //5.向tcp服务器发送数据：应该在连接到服务器后在发送数据，因此在连接到tcp服务器的回调函数中完成
  client.write('hello server!');
});
//4.获取服务端发送过来的数据：监听data事件：
client.on('data', (data) => {
  console.log('接收到服务端数据为：' + data);
  const buf = Buffer.from(data).toString('utf8');
  if (buf.startsWith('{data')) {
    const key = buf[5];
    const count = Number(buf.slice(8, buf.length - 2));
    let obj = {};
    switch (key) {
      case HENHOUSE_A:
      case HENHOUSE_B:
      case HENHOUSE_C:
        obj = {
          'henhouse-type': henhouseMap.get(key),
          count
        };
        axios
          .post('http://119.91.26.59:1235/henhouse/saveHenhouseType', obj)
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case QUALITY_A:
      case QUALITY_B:
      case QUALITY_C:
        obj = {
          'henhouse-quality': henhouseMap.get(key),
          count
        };
        axios
          .put('http://119.91.26.59:1235/henhouse/saveHenhouseQuality', obj)
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      default:
        return;
    }
  } else {
    const [temperature, humidity] = buf.split(' ');
    console.log(
      JSON.stringify({
        temperature: Number(temperature),
        humidity: Number(humidity),
        'save-datetime': getDate(new Date())
      })
    );
    // 上报温度
    axios
      .put(
        'http://119.91.26.59:1235/temperatureAndHumidity/saveTemperatureAndHumidity',
        {
          temperature: Number(temperature),
          humidity: Number(humidity)
        }
      )
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
});
//6.end事件用于监听客户端发送数据完成：
client.on('end', (data) => {
  console.log('向服务端发送数据完成', data);
});
